package com.dorukdestan.p2pshare.network;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.net.Socket;

import com.dorukdestan.p2pshare.logger.Logger;
import com.dorukdestan.p2pshare.model.Constants;
import com.dorukdestan.p2pshare.model.Protocol;
import com.dorukdestan.p2pshare.model.SharedFile;
import com.dorukdestan.p2pshare.storage.SharedFoldersAndFiles;

public class SendingProcess implements Runnable{
	
	private Logger logger;
	private String fileHash;
	private String fileIndexStart;
	private String fileIndexEnd;
	private InetAddress peerAddress;
	
	public SendingProcess(String fileHash, String fileIndexStart,
			String fileIndexEnd, InetAddress peerAddress) {
		this.fileHash = fileHash;
		this.fileIndexStart = fileIndexStart;
		this.fileIndexEnd = fileIndexEnd;
		this.peerAddress = peerAddress;
		logger = new Logger(getClass());
	}

	@Override
	public void run() {
		logger.debug("sending chunk");
		Socket socket = null;
		try {
			socket = new Socket(peerAddress, Constants.TCP_PORT_NUMBER);
			socket.setReuseAddress(true);
			DataOutputStream output = new DataOutputStream(
					socket.getOutputStream());
			
			//Find file
			SharedFile file = SharedFoldersAndFiles.sharedFiles.get(Long.parseLong(fileHash));
			
			//TODO Split into chunks
			long startIndex = Long.parseLong(fileIndexStart);
			long endIndex = Long.parseLong(fileIndexEnd);
			
			RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
			
			long numberOfChunks = (endIndex - startIndex + 1) / Constants.FILE_CHUNK_SIZE;
			numberOfChunks = numberOfChunks % Constants.FILE_CHUNK_SIZE == 0 ? numberOfChunks : numberOfChunks + 1;
			
			logger.debug("forValue"+(numberOfChunks % Constants.FILE_CHUNK_SIZE == 0 ? numberOfChunks : numberOfChunks + 1));
			logger.debug("numberOfChunks "+numberOfChunks);
			
			for (int i = 0; i < numberOfChunks; i++) {
				byte[] data = new byte[Constants.FILE_CHUNK_SIZE];
				
				logger.debug("startIndex= " + i*Constants.FILE_CHUNK_SIZE + " | " + "endIndex= "
						+ (i*Constants.FILE_CHUNK_SIZE + Constants.FILE_CHUNK_SIZE));
				
				randomAccessFile.seek(i*Constants.FILE_CHUNK_SIZE);
				randomAccessFile.read(data, 0 , Constants.FILE_CHUNK_SIZE);
				
				//Create query
				String protocolQuery = Protocol.SENDING_FILE
						+ Protocol.DELIMINATOR_CHAR + fileHash
						+ Protocol.DELIMINATOR_CHAR + i*Constants.FILE_CHUNK_SIZE
						+ Protocol.DELIMINATOR_CHAR + new String(data).toString();
				//Send
				output.writeBytes(protocolQuery);
				output.flush();
			}
		} catch (Exception e) {
			logger.error(e);
		} finally{
			if(socket != null)
				try {
					socket.close();
				} catch (IOException e) {
					logger.error(e);
				}
		}
	}
}
